﻿using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eslib.nnp5.Protobuf
{

    /// <summary>
    /// protobuf数据包
    /// </summary>
    /// <typeparam name="T">派生自Google.Protobuf.IMessage的类</typeparam>
    public class ProtobufPkg<T> : IPackage
        where T : IMessage, new()
    {
        /// <summary>
        /// 绑定的对象
        /// </summary>
        public T Obj { get; private set; }




        /// <summary>
        /// 以protobuf对象创建数据包
        /// </summary>
        /// <param name="protobufObject"></param>
        public ProtobufPkg(T protobufObject)
        {
            this.Obj = protobufObject;
        }


        private ProtobufPkg() { }


        /// <summary>
        /// 序列化数据包
        /// </summary>
        /// <returns></returns>
        public byte[] GetBuffer()
        {
            //序列化
            return Obj.ToByteArray();
        }


        /// <summary>
        /// 以反序列化方式从数据包缓存构造
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static ProtobufPkg<T> Create(byte[] buffer)
        {
            var pkg = new ProtobufPkg<T>();
            pkg.Obj = new T();
            pkg.Obj.MergeFrom(buffer);      //反序列化
            return pkg;
        }
    }
}
